import React, { Component, createRef } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons';
import Captcha from '../../component/Captcha';
// 导入资源组件
import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from "react-router-dom"

class Mobile extends Component {
  constructor(props) {
    super(props)
    this.capRef = createRef()
    this.formRef = createRef()
  }
  state = {
    time: 10, //倒计时
    sentCode: false, //判断是否已经获取到短信
    enabled: true //获取短信按钮是否可点击
  }
  t = null
  render() {
    return (
      <div>
        <div>
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{}}
            ref={this.formRef}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '请填写手机号',
                },
              ]}
            >
              <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
            </Form.Item>

            <Form.Item
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请填写验证码',
                },
              ]}
            >
              <div>
                <Input
                  prefix={<KeyOutlined className="site-form-item-icon" />}
                  type="text"
                  placeholder="验证码"
                  style={{ width: "70%", marginRight: "5px" }}
                />
                <Captcha w={96} h={32} setKey={this.getKey} ref={this.capRef}></Captcha>
              </div>
            </Form.Item>

            <Form.Item
               name="code"
               rules={[
                 {
                   required: true,
                   message: '请填写短信验证码',
                 },
               ]}
             >
               <div>
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="text"
                  placeholder="短信验证码"
                  style={{ width: "60%", marginRight: "5px" }}
                />
                <Button type="primary" onClick={this.sendCode.bind(this)} disabled={!this.state.enabled} style={{ width: "38%" }}>
                  { this.state.enabled ? "获取短信" : `重新获取${this.state.time}` }
                </Button>
               </div>
             </Form.Item>

            <Form.Item>
              <Button disabled={!this.state.sentCode} type="primary" htmlType="submit" className="login-form-button" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }

  getKey = (key) =>  {
    this.setState({
      key
    })
  }

  onFinish = (values) => {
   let { mobile, code } = values
   let params = { mobile, code, requestId: this.state.requestId }
  //  console.log(params)
   req.post(url.MobileLogin, params)
    .then(res => {
      if (res.data.errNo === 0) {
        message.success("登录成功", 2, () => {
          this.props.history.push("/dashboard")
        })
      } else {
        message.error(res.data.errText, 2, () => {
          this.capRef.current.loadCaptcha()
        })
      }
    })
  }

  sendCode () {
    let { mobile, captcha } = this.formRef.current.getFieldsValue()
    if (/^1[3-9]\d{9}$/.test(mobile) && captcha) {
      // 手机号格式没问题，并且有图形验证码
      req.post(url.VerifyCaptcha, { captcha, key: this.state.key })
        .then((res) => {
          if (res.data.errNo === 0) {
            let token = res.data.context.token
            // 短信下发
            req.post(url.SendCode, { mobile, token, type: 0 })
              .then(ret => {
                if (ret.data.errNo === 0) {
                  this.setState({
                    requestId: ret.data.requestId,
                    sentCode: true
                  })
                  message.success("短信发送成功", 2)
                  this.timeDown()
                } else {
                  message.error(res.data.errText, 2, () => {
                    this.capRef.current.loadCaptcha()
                  })
                }
              })
          }
        })
    } else {
      message.error("请正确填写手机号及图形验证码")
    }
  }

  timeDown () {
    if (this.state.time === 0) {
      this.setState({
        time: 60,
        enabled: true
      })
    } else {
      this.setState({
        time: this.state.time - 1,
        enabled: false
      })
      this.t = setTimeout(() => {
        this.timeDown()
      }, 1000)
    }
  }
  
  componentWillUnmount () {
    clearTimeout(this.t)
  }
}

export default withRouter(Mobile);
